/**
 * 导航跳转工具函数
 * 统一管理页面跳转逻辑，特别是详情页跳转
 */

import { Router, RouteLocationNormalizedLoaded } from 'vue-router';
import { onMounted, onUnmounted } from 'vue';

/**
 * 跳转到详情页面
 * @param router Vue Router实例
 * @param id 记录ID
 * @param type 类型标识 (1-合同，2-报销，3-付款)
 * @param fallbackRoute 如果没有id和type时的备用路由
 */
export const navigateToDetail = (
  router: Router,
  id?: string,
  type?: string,
  fallbackRoute?: string,
  from?: 'home' | 'approvals' | 'add'
) => {
  if (!id || !type) {
    // 如果没有id和type，跳转到备用路由或返回上一页
    if (fallbackRoute) {
      router.push(fallbackRoute);
    } else {
      router.back();
    }
    return;
  }

  // 根据type确定跳转的详情页面
  let detailRoute = '';
  switch (type) {
    case '1': // 合同
      detailRoute = `/contract/detail/${id}?type=${type}${from ? `&from=${from}` : ''}`;
      break;
    case '2': // 报销
      detailRoute = `/expense/detail/${id}?type=${type}${from ? `&from=${from}` : ''}`;
      break;
    case '3': // 付款
      detailRoute = `/contract/detail/pay-detail/${id}?type=${type}${from ? `&from=${from}` : ''}`;
      break;
    default:
      console.warn(`未知的类型: ${type}`);
      if (fallbackRoute) {
        router.push(fallbackRoute);
      } else {
        router.back();
      }
      return;
  }

  router.push(detailRoute);
};

/**
 * 根据API响应跳转到相应页面
 * @param router Vue Router实例
 * @param response API响应对象
 * @param fallbackRoute 备用路由
 * @param delay 延迟时间（毫秒）
 */
export const navigateAfterSubmit = (
  router: Router,
  response: { data?: { id?: string; type?: string } },
  fallbackRoute?: string,
  delay: number = 1500
) => {
  setTimeout(() => {
    if (response.data?.id && response.data?.type) {
      // 从新增页面提交后进入详情，统一标记 from=add，便于详情页按需返回审批页
      navigateToDetail(router, response.data.id, response.data.type, fallbackRoute, 'add');
    } else {
      if (fallbackRoute) {
        router.push(fallbackRoute);
      } else {
        router.back();
      }
    }
  }, delay);
};

/**
 * 获取详情页面标题
 * @param type 类型标识
 * @returns 页面标题
 */
export const getDetailPageTitle = (type: string): string => {
  switch (type) {
    case '1':
      return '合同详情';
    case '2':
      return '报销详情';
    case '3':
      return '付款详情';
    default:
      return '详情';
  }
};

/**
 * 获取业务类型名称
 * @param type 类型标识
 * @returns 业务类型名称
 */
export const getBusinessTypeName = (type: string): string => {
  switch (type) {
    case '1':
      return '合同';
    case '2':
      return '报销';
    case '3':
      return '付款';
    default:
      return '未知';
  }
};

/**
 * 智能返回函数 - 根据当前路由和参数决定返回逻辑
 * @param router Vue Router实例
 * @param defaultPath 默认返回路径
 */
export const smartGoBack = (router: Router, defaultPath: string = '/home') => {
  const currentRoute = router.currentRoute.value;
  const currentPath = currentRoute.path;
  const query = currentRoute.query;
  
  // 新增页面 - 返回到首页
  const addPages = [
    '/expense/add',
    '/organization/add-member', 
    '/organization/add-department',
    '/contract/addPay'
  ];
  
  if (addPages.includes(currentPath)) {
    router.push('/home');
    return;
  }
  
  // 详情页面 - 根据URL参数返回到对应的审批列表
  const detailPages = [
    '/expense/detail',
    '/contract/detail'
  ];
  
  const isDetailPage = detailPages.some(page => currentPath.startsWith(page));
  if (isDetailPage && query.tab) {
    router.push(`/approvals?tab=${query.tab}`);
    return;
  }
  
  // 组织深层页面特殊处理
  if (currentPath === '/organization/set-manager') {
    // 从URL参数或referrer获取部门信息
    const departmentId = query.departmentId || query.id;
    const departmentName = query.departmentName;
    
    if (departmentId) {
      const returnUrl = `/organization/department/${departmentId}`;
      if (departmentName) {
        router.push(`${returnUrl}?departmentName=${encodeURIComponent(departmentName as string)}`);
      } else {
        router.push(returnUrl);
      }
      return;
    }
  }
  
  // 编辑页面 - 返回到对应的详情或列表页
  if (currentPath.includes('/edit-member')) {
    const departmentId = query.departmentId;
    const departmentName = query.departmentName;
    
    if (departmentId) {
      const returnUrl = `/organization/department/${departmentId}`;
      if (departmentName) {
        router.push(`${returnUrl}?departmentName=${encodeURIComponent(departmentName as string)}`);
      } else {
        router.push(returnUrl);
      }
      return;
    }
  }
  
  // 检查是否有历史记录可以返回
  if (window.history.length > 1) {
    // 直接返回上一页，不再检查 referrer
    router.back();
    return;
  }
  
  // 如果没有历史记录，且当前不在首页，则返回首页
  if (currentPath !== '/home') {
    router.push(defaultPath);
  }
};

/**
 * 计算详情页的返回目标
 * 规则：
 * - query.from === 'home' -> 返回 '/home'
 * - query.from === 'approvals' 或 'add' -> 返回 '/approvals'
 * - 其他情况 -> 默认返回 '/home'
 */
export const getDetailBackTarget = (route: RouteLocationNormalizedLoaded): string => {
  const fromParam = (route.query?.from as string) || '';
  if (fromParam === 'home') return '/home';
  if (fromParam === 'approvals' || fromParam === 'add') return '/approvals';
  return '/home';
};

/**
 * 在详情页内启用智能返回（左滑/系统返回）重定向
 * 当从“新增页”进入详情（from=add）时，系统返回会先退到新增页，
 * 这里监听全局 router:navigation 事件，一旦检测到从详情页发生后退，
 * 若应返回审批页则立即重定向到 '/approvals'，其余情况保持原历史返回。
 */
export const useSmartDetailBack = (router: Router, route: RouteLocationNormalizedLoaded) => {
  const onNav = (ev: Event) => {
    try {
      const custom = ev as CustomEvent;
      const detail = (custom && custom.detail) || {};
      const { to, from, isBack } = detail;

      // 仅处理“从详情页后退”的场景
      const fromName = from?.name as string | undefined;
      const isDetailFrom = fromName === 'contract-detail' || fromName === 'expense-detail' || fromName === 'pay-detail';
      if (!isBack || !isDetailFrom) return;

      // 期望返回目标（依赖进入详情时带上的 query.from）
      const target = getDetailBackTarget(from);

      // 如果后退后已在目标页，忽略；否则重定向到目标页
      const toPath = to?.path as string | undefined;
      if (toPath && (toPath === target)) return;

      router.push(target).catch(() => {});
    } catch (e) {
      // 忽略错误，确保不影响正常导航
      console.warn('[useSmartDetailBack] 处理导航事件失败:', e);
    }
  };

  onMounted(() => {
    window.addEventListener('router:navigation', onNav);
  });
  onUnmounted(() => {
    window.removeEventListener('router:navigation', onNav);
  });
};

/**
 * 全局规则：当从 /approvals 页面执行“后退”（硬件返回/左滑）时，统一重定向到首页 /home
 * 解决：从详情返回到 /approvals 后再次后退又回到详情页的循环问题
 */
export const installApprovalsBackToHome = (router: Router) => {
  const onNav = (ev: Event) => {
    try {
      const custom = ev as CustomEvent;
      const detail = (custom && custom.detail) || {};
      const { to, from, isBack } = detail;

      if (!isBack) return;

      const fromPath = (from?.path as string) || '';
      const fromName = (from?.name as string) || '';
      const isFromApprovals = fromPath === '/approvals' || fromName === 'approvals';
      if (!isFromApprovals) return;

      const currentPath = router.currentRoute.value.path;
      if (currentPath !== '/home') {
        router.push('/home').catch(() => {});
      }
    } catch (e) {
      console.warn('[installApprovalsBackToHome] 处理导航事件失败:', e);
    }
  };

  // 全局注册一次，无需卸载
  window.addEventListener('router:navigation', onNav);
};